#include "rc4.h"
#include "qdebug.h"
#include <iostream>
#include <fstream>
#include <QtGlobal>

Rc4::Rc4(std::string k)
{
    key =k;
    keylen = key.length();
    qDebug()<<"len "<<keylen;
}

void Rc4::initial() {
    for(int i=0;i<256;++i){
        S[i]=i;
        T[i]=key[i%keylen];
    }
}

void Rc4::ksa() {
    int j=0;
    for(int i=0;i<256;i++){
        j=(j+S[i]+T[i])%256;
        //cout<<"j="<<j<<endl;
        std::swap(S[i],S[j]);
    }
}

void Rc4::prga(int len) {
    initial();
    ksa();

    int i=0,j=0,t;
    while(len>=0){
        len--;
        i=(i+1)%256;
        j=(j+S[i])%256;
        std::swap(S[i],S[j]);

        t=(S[i]+S[j])%256;
        fullkey.push_back(S[t]);
    }
}

void Rc4::encrypt(const std::string plaintext, const std::string ciphertext) {
    std::ifstream in,temp;
    std::ofstream out;

    in.open(plaintext.c_str());

    in.seekg(0,in.end);
    int lenFile=in.tellg();

    in.seekg(0, in.beg);

    prga(lenFile);


    unsigned char *bits=new unsigned char[lenFile];
    in.read((char*) bits,lenFile);
    in.close();

    out.open(ciphertext.c_str(),std::ios_base::out|std::ios_base::binary);
    for(int i=0;i<lenFile;++i){
        out<<(unsigned char)(bits[i]^fullkey[i]);

    }
    out.close();
    temp.open(ciphertext.c_str());

    temp.seekg(0,temp.end);
    qDebug()<<"after"<<temp.tellg();

    temp.close();
}
